package com.jackie.jjface;

import java.io.IOException;

import android.app.Activity;
import android.hardware.Camera;
import android.hardware.Camera.CameraInfo;
import android.hardware.Camera.Face;
import android.hardware.Camera.FaceDetectionListener;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author Administrator
 *
 */
public class MainActivity extends Activity {
	private static final String TAG = MainActivity.class.getSimpleName();

	/**
	 * 监测当前摄像头是否为前置摄像头
	 */
	private boolean isFront = false;

	private static int mDegrees = 0;

	/**
	 * 摄像头对象
	 */
	private Camera mCamera;

	/**
	 * 提示内容
	 */
	private TextView tvContext;

	/**
	 * 预览窗口
	 */
	private SurfaceView suDetect;

	Callback mCallback = new Callback() {

		@Override
		public void surfaceDestroyed(SurfaceHolder holder) {
			Log.i(TAG, "surfaceDestroyed");
			/** 停止人脸监测 */
			//mCamera.stopFaceDetection();
			/** 停止摄像头预览 */
			mCamera.stopPreview();
		}

		@Override
		public void surfaceCreated(SurfaceHolder holder) {
			Log.i(TAG, "surfaceCreated");
			try {
				/** 设置预览视图展示区 */
				mCamera.setPreviewDisplay(holder);
				/** 开启摄像头预览 */
				mCamera.startPreview();
				/** 开启人脸监测 */
				//mCamera.startFaceDetection();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		@Override
		public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
			Log.i(TAG, "surfaceChanged");
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		mDegrees = getDegrees();

		tvContext = (TextView) findViewById(R.id.tv_context);
		suDetect = (SurfaceView) findViewById(R.id.sv_detect);

		/** 获取摄像头对象 */
		mCamera = Camera.open();
		Toast.makeText(this, "有 " + Camera.getNumberOfCameras() + " 个摄像头，", Toast.LENGTH_LONG).show();
		isFront = false;
	}

	@Override
	protected void onResume() {
		super.onResume();
		if (mCamera != null) {
			/** 开始监测人头像 */
			startDetectedFace(mCamera);
			/** 预览摄像头 */
			perview(mCamera, mCallback, suDetect);
		} else {
			Log.i(TAG, "摄像头没取到！！！");
			Toast.makeText(this, "摄像头没取到！！！", Toast.LENGTH_LONG).show();
		}
	}
	
	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (mCamera != null) {
			/** Activity退出释放摄像头 */
			mCamera.release();
		} else {
			Log.i(TAG, "摄像头没取到！！！");
			Toast.makeText(this, "摄像头没取到！！！", Toast.LENGTH_LONG).show();
		}
	}

	/**
	 * 视图点击事件在XML中定义android:onClick="onClick"<br>
	 * 时在Activity中实现此函数<br>
	 * 
	 * @param view
	 *            被点击的视图控件
	 */
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.btn_switch_camera:// 切换相机的按钮
			
			if (mCamera == null) {
				Log.i(TAG, "摄像头没取到！！！");
				Toast.makeText(this, "摄像头没取到！！！", Toast.LENGTH_LONG).show();
				return;
			}
			
			/** 停止人脸监测 */
			//mCamera.stopFaceDetection();
			/** 停止摄像头预览 */
			mCamera.stopPreview();
			/** 释放上一个摄像头资源 */
			mCamera.release();

			if (isFront) {// 前置摄像头切换到后置摄像头
				// mCamera.stopFaceDetection();
				mCamera = Camera.open(CameraInfo.CAMERA_FACING_BACK);
				isFront = false;
			} else {// 后置摄像头切换到前置摄像头
				mCamera = Camera.open(CameraInfo.CAMERA_FACING_FRONT);
				isFront = true;
			}

			try {
				/** 设置预览视图展示区 */
				mCamera.setPreviewDisplay(suDetect.getHolder());
			} catch (IOException e) {
				e.printStackTrace();
			}

			startDetectedFace(mCamera);

			/** 开启摄像头预览 */
			mCamera.startPreview();

			/** 开启人脸监测 */
			//mCamera.startFaceDetection();

			/** 设置显示视图的旋转角度 */
			mCamera.setDisplayOrientation(mDegrees);
			break;

		case R.id.ib_degrees:// 旋转成像
			setDegrees(90, mCamera);
			break;

		default:
			break;
		}
	}

	/**
	 * 初始化人脸监测
	 * 
	 * @param camera
	 *            - 被监测的摄像头
	 */
	private void startDetectedFace(Camera camera) {

		/** 获取摄像头能监测到的最大人脸数 */
		int facesDetectable = mCamera.getParameters().getMaxNumDetectedFaces();
		Log.i(TAG, "initDetectedFace& facesDetectable = " + facesDetectable);
		tvContext.setText("facesDetectable is " + facesDetectable);

		/** 监听并跟踪人脸识别 */
		camera.setFaceDetectionListener(new FaceDetectionListener() {

			@Override
			public void onFaceDetection(Face[] faces, Camera camera) {
				Log.i(TAG, "initDetectedFace& faces.length = " + faces.length);
				/** 显示识别的人数 */
				tvContext.setText("detected are " + faces.length);

				/** face列表不为空并且长度大于0，代表监听到人脸 */
				if (faces != null && faces.length > 0) {
					String comma = "; ";
					for (Face face : faces) {
						StringBuilder sb = new StringBuilder();
						sb.append(face.id).append(comma);
						sb.append(face.score).append(comma);
						sb.append(face.toString()).append(comma);
						Log.i(TAG, sb.toString());
					}
				}
			}
		});
	}

	/**
	 * 添加预览
	 * 
	 * @param camera
	 *            - 摄像头
	 * @param callback
	 *            - 回调
	 * @param sufaceView
	 *            - 预览视图显示区
	 */
	private void perview(Camera camera, Callback callback, SurfaceView sufaceView) {
		camera.setDisplayOrientation(mDegrees);
		SurfaceHolder sHolder = sufaceView.getHolder();
		sHolder.addCallback(callback);
	}

	/**
	 * 获取图像旋转角度
	 * 
	 * @return
	 */
	private int getDegrees() {
		int degrees = PreferenceManager.getDefaultSharedPreferences(this).getInt("degrees", 0);
		return degrees;
	}

	/**
	 * 设置旋转角度最大不能超过360度
	 * 
	 * @param changeValue
	 *            - 角度改变的度数
	 */
	private void setDegrees(int changeValue, Camera camera) {
		if (camera == null) {
			Log.i(TAG, "摄像头没取到！！！");
			Toast.makeText(this, "摄像头没取到！！！", Toast.LENGTH_LONG).show();
			return;
		}
		/** 最大不能超过360度，所以对360取模 */
		mDegrees = (mDegrees + changeValue) % 360;

		/** 存储最终改变的角度 */
		PreferenceManager.getDefaultSharedPreferences(this).edit().putInt("degrees", mDegrees);

		/** 切换至当前设置改变后的角度 */
		camera.setDisplayOrientation(mDegrees);
	}

}
